//
//  QHttpManager.m
//  QoilPublic
//
//  Created by 杨凯 on 16/7/1.
//  Copyright © 2016年 杨凯. All rights reserved.
//

#import "QHttpManager.h"
#import "QMD5Hash.h"
#import "QShowAlertView.h"
static NSString *keyTimeoutInterval = @"timeoutInterval";

//static NSString *authStr = @"sevalo_oil!@#$%^&*()";
@interface QHttpManager()

@end
@implementation QHttpManager

+ (QHttpManager *)sharedManager{
    static QHttpManager *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc]init];
    });
    return sharedInstance;
}

+ (AFHTTPSessionManager *)baseSetUp{
    AFHTTPSessionManager *manager = [QHttpManager sharedManager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    [manager.requestSerializer willChangeValueForKey:keyTimeoutInterval];
    manager.requestSerializer.timeoutInterval = 12;
    [manager.requestSerializer didChangeValueForKey:keyTimeoutInterval];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    return manager;
}

#pragma mark -- 普通的网络请求
- (void)POST:(NSString *)urlPath
  parameters:(id)params
  completion:(void(^)(NSData *data, NSDictionary *dict, NSError *error))completion {
    
    AFHTTPSessionManager *manager = [QHttpManager baseSetUp];
    [manager POST:urlPath parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        
        NSString *responseStr = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSString *methodName = [[urlPath componentsSeparatedByString:@"/"] lastObject];
        CLog(@"== %@:%@",methodName,responseStr);
        if (completion) {
            completion(responseObject, dict, nil);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSHTTPURLResponse * response = (NSHTTPURLResponse *)task.response;
        NSInteger statusCode = response.statusCode;
        
        if(statusCode == 404){
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:@"您所访问的页面不存在！请稍后再试!" btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
        }else if (statusCode == 504){
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:@"服务器暂时失去响应，请稍后再试!" btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
        }
        else if (statusCode == 503){
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:@"服务器正在维护中，请稍后再试!" btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
        }else{
            if([QUserInfo sharedInfo].isHaveNetWork == YES){
                [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:@"服务器暂时失去响应，请稍后再试!" btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
            }else{
                [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:@"无法连接到网络,请检查网络设置" btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
            }
        }
        if (completion) {
            completion(nil, nil, error);
        }
    }];
}

#pragma mark --- 2.0加密请求
- (void)POST:(NSString *)urlPath
  parameterMD5:(id)params
  completion:(void(^)(NSData *data, NSDictionary *dict, NSError *error))completion{

    AFHTTPSessionManager *manager = [QHttpManager baseSetUp];
    
    [manager.requestSerializer setValue:@"en-en/ZTEX850/android2.1/320X480/11111111111111" forHTTPHeaderField:@"phone_agent"];
    [manager.requestSerializer setValue:@"447448100076" forHTTPHeaderField:@"MSISDN"];
    [manager.requestSerializer setValue:@"1.0" forHTTPHeaderField:@"version"];
    [manager.requestSerializer setValue:@"1.0.1" forHTTPHeaderField:@"innerVersion"];
    [manager.requestSerializer setValue:@"WIFI" forHTTPHeaderField:@"netMode"];
    
    
    NSString *jsonS = [QParamService dictToString:params];
    NSDictionary *requestParams = @{@"jsonData":jsonS};
    
    NSString *formatStr = [NSString stringWithFormat:@"%@",jsonS];
    NSString *md5Str = [QMD5Hash md5String:formatStr];
    md5Str = [md5Str uppercaseString];
    [manager.requestSerializer setValue:md5Str forHTTPHeaderField:@"authorization"];
    NSString *rStr = [NSString stringWithFormat:@"%ld",(unsigned long)jsonS.length];
    [manager.requestSerializer setValue:rStr forHTTPHeaderField:@"oilAppCode"];
    
    [manager POST:urlPath parameters:requestParams progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        
        NSString *responseStr = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSString *methodName = [[urlPath componentsSeparatedByString:@"/"] lastObject];
        CLog(@"== %@:%@",methodName,responseStr);
        if (completion) {
            completion(responseObject, dict, nil);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
       // NSHTTPURLResponse *response = error.userInfo[AFNetworkingOperationFailingURLResponseErrorKey];
        NSHTTPURLResponse * response = (NSHTTPURLResponse *)task.response;
        NSInteger statusCode = response.statusCode;
        [QViewUtility disMissNoNetWorkInVC:[QViewUtility getCurrentVC]];
        if(statusCode == 404){
                
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:@"您所访问的页面不存在！请稍后再试!" btnTitle:showAlertBtnTitle type:1 myBlock:^{
                NSLog(@"----------%@---------",[QViewUtility getCurrentVC]);
            }];
        }else if (statusCode == 504){
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:@"服务器暂时失去响应，请稍后再试!" btnTitle:showAlertBtnTitle type:1 myBlock:^{
            
            NSLog(@"111111111%@111111111",[QViewUtility getCurrentVC]);
            }];
        }
        else if (statusCode == 503){
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:@"服务器正在维护中，请稍后再试!" btnTitle:showAlertBtnTitle type:1 myBlock:^{
            
            NSLog(@"111111111%@111111111",[QViewUtility getCurrentVC]);
            }];
        }else{
            if([QUserInfo sharedInfo].isHaveNetWork == YES){
                 [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:@"服务器暂时失去响应，请稍后再试!" btnTitle:showAlertBtnTitle type:1 myBlock:^{
                 NSLog(@"111111111%@111111111",[QViewUtility getCurrentVC].view);
                 }];
            }else{
                
                UIViewController *vc = [QViewUtility getCurrentVC];
                for (UIView *subView in vc.view.subviews) {
                    
                    NSLog(@"subView:%@",subView);
                    if ([subView isKindOfClass:[MBProgressHUD class]]) {
                        NSLog(@"2222222");
                        [subView removeFromSuperview];
                    }
                    if ([subView isKindOfClass:[QShowAlertView class]]) {
                        NSLog(@"3333333");
                    }
                    
                }
                
                [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:@"无法连接到网络,请检查网络设置" btnTitle:showAlertBtnTitle type:1 myBlock:^{
                }];
            }
        }
        
        if (completion) {
            completion(nil, nil, error);
        }
    }];
}

#pragma mark --- 2.0加密请求  加满
- (void)POST:(NSString *)urlPath
parameterMD5jm:(id)params
  completion:(void(^)(NSData *data, NSDictionary *dict, NSError *error))completion{
    
    AFHTTPSessionManager *manager = [QHttpManager baseSetUp];
    
    [manager.requestSerializer setValue:@"en-en/ZTEX850/android2.1/320X480/11111111111111" forHTTPHeaderField:@"phone_agent"];
    [manager.requestSerializer setValue:@"447448100076" forHTTPHeaderField:@"MSISDN"];
    [manager.requestSerializer setValue:@"1.0" forHTTPHeaderField:@"version"];
    [manager.requestSerializer setValue:@"1.0.1" forHTTPHeaderField:@"innerVersion"];
    [manager.requestSerializer setValue:@"WIFI" forHTTPHeaderField:@"netMode"];
    
    
    NSString *jsonS = [QParamService dictToString:params];
    NSDictionary *requestParams = @{@"jsonData":jsonS};
    
    NSString *formatStr = [NSString stringWithFormat:@"%@",jsonS];
    NSString *md5Str = [QMD5Hash md5String:formatStr];
    md5Str = [md5Str uppercaseString];
    [manager.requestSerializer setValue:md5Str forHTTPHeaderField:@"authorization"];
    NSString *rStr = [NSString stringWithFormat:@"%ld",(unsigned long)jsonS.length];
    [manager.requestSerializer setValue:rStr forHTTPHeaderField:@"oilAppCode"];
    
    [manager POST:urlPath parameters:requestParams progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        
        NSString *responseStr = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSString *methodName = [[urlPath componentsSeparatedByString:@"/"] lastObject];
        CLog(@"== %@:%@",methodName,responseStr);
        if (completion) {
            completion(responseObject, dict, nil);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (completion) {
            completion(nil, nil, error);
        }
    }];
}


#pragma mark --- 上传文件
- (void)uploadFile:(NSString*)urlTokenPath
            params:(id)params
             image:(UIImage*)img
        completion:(void(^)(NSData *data, NSDictionary *dict, NSError *error))completion{
    
    NSData *imgData = UIImageJPEGRepresentation(img, 1);
    if(imgData.length>1024*1024*2){
        imgData = UIImageJPEGRepresentation(img, .5);
    }
    AFHTTPSessionManager *manager = [QHttpManager baseSetUp];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *str = [formatter stringFromDate:[NSDate date]];
    NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
    
    [manager POST:urlTokenPath parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:imgData name:@"headImg" fileName:fileName mimeType:@"Image/Jpeg"];
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        completion(responseObject, dict, nil);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        completion(nil, nil, error);
        
        
    }];
}


//上传文件
- (void)upLoadData:(NSString *)urlPath
            params:(id)params
              data:(NSData *)data
          fileName:(NSString *)fileName
        completion:(void(^)(NSData *data, NSDictionary *dict, NSError *error))completion{
    
    AFHTTPSessionManager *manager = [QHttpManager baseSetUp];

    [manager POST:urlPath parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        [formData appendPartWithFileData:data name:@"img" fileName:fileName mimeType:@"application/octet-stream"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        CLog(@"%f",1.0 *uploadProgress.completedUnitCount/uploadProgress.totalUnitCount);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        completion(responseObject, dict, nil);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        completion(nil, nil, error);
    }];

}


#pragma mark -- 请求记账本
- (void)update:(NSString *)urlPath completion:(void(^)(NSData *data, NSArray *arr, NSError *error))completion{
    
    AFHTTPSessionManager *manager = [QHttpManager baseSetUp];
    manager.requestSerializer.HTTPShouldHandleCookies = NO;
    manager.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
    
    [manager POST:urlPath parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *responseStr = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSArray *a = (NSArray *)[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSString *methodName = [[urlPath componentsSeparatedByString:@"/"] lastObject];
            CLog(@"== %@:%@",methodName,responseStr);
            if (completion) {
                completion(responseObject, a, nil);
            }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (completion) {
            completion(nil, nil, error);
        }
    }];
}

- (void)updateData:(NSString *)urlPath completion:(void(^)(NSData *data, NSDictionary *dic, NSError *error))completion{
    AFHTTPSessionManager *manager = [QHttpManager baseSetUp];
    manager.requestSerializer.HTTPShouldHandleCookies = NO;
    manager.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
    
    [manager POST:urlPath parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *d = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        if (completion) {
            completion(responseObject, d, nil);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (completion) {
            completion(nil, nil, error);
        }
    }];
}


//上传多张照片免费办证
- (void)uploadMorePhone:(NSString*)urlTokenPath
            params:(id)params
             array:(NSArray *)array
        completion:(void(^)(NSData *data, NSDictionary *dict, NSError *error))completion{
    
    AFHTTPSessionManager *manager = [QHttpManager baseSetUp];

    [manager POST:urlTokenPath parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for (int i=0; i<array.count; ++i) {
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString stringWithFormat:@"%ld.jpg", [str integerValue]+1];

            NSString *name;
            if(i == 0){//登记照
                name = @"registerFile";
            }else if (i == 1){//身份证正面
                name = @"certificatesFrontFile";
            }else if (i == 2){//身份证背面
                name = @"certificatesBackFile";
            }
             [formData appendPartWithFileData:array[i] name:name fileName:fileName mimeType:@"Image/Jpeg"];
        }
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        completion(responseObject, dict, nil);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        completion(nil, nil, error);
    }];
}

@end
